import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'  

const routes = [
  {
    path: '/',
    redirect: '/dashboard',
    meta: { title: '首页' }
  },
  {
    path: '/login',
    name: 'Login',
    meta: { title: '登录' },
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    component: () => import('../components/AdminLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        meta: { title: '首页' },
        component: () => import('../views/Dashboard.vue')
      },
      {
        path: 'users',
        name: 'UserList',
        meta: { title: '用户列表' },
        component: () => import('../views/UserList.vue')
      },
      {
        path: 'roles',
        name: 'RoleList',
        meta: { title: '角色管理' },
        component: () => import('../views/RoleList.vue')
      },
      {
        path: 'settings',
        name: 'Settings',
        meta: { title: '系统设置' },
        component: () => import('../views/Settings.vue')
      },
      {
        path: 'logs',
        name: 'LogList',
        meta: { title: '操作日志' },
        component: () => import('../views/LogList.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next({ name: 'Login' })
  } else if (to.name === 'Login' && authStore.isAuthenticated) {
    next({ name: 'Dashboard' })
  } else {
    next()
  }
})

export default router